package com.huage_06.cookie;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = response.getWriter();
        long time = 0L;
        if (cookies != null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if("time".equals(name)){
                    String value = cookie.getValue();
                     time = Long.parseLong(value);

                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = df.format(time);
                    pw.write("欢迎回来，你上次访问时间为"+date);
                    break;
                }
            }
        }
        if (time==0){
            pw.write("欢迎你,首次访问");
        }

        time = new Date().getTime();
        Cookie cookie = new Cookie("time",time+"");
        cookie.setMaxAge(600);
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
